package org.ktx.osr

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import org.ktx.osr.service.ScreenRecordingService
import org.ktx.osr.ui.theme.MyApplicationTheme

/**
 * 透明的权限处理Activity
 * 负责处理屏幕录制权限请求和启动录制服务
 */
class PermissionActivity : ComponentActivity() {
    
    private var mediaProjectionManager: MediaProjectionManager? = null
    private var hasOverlayPermission = false
    private var hasAudioPermission = false
    
    companion object {
        private const val TAG = "PermissionActivity"
        
        const val EXTRA_ACTION = "action"
        const val ACTION_START_RECORDING = "start_recording"
        const val ACTION_STOP_RECORDING = "stop_recording"
        const val ACTION_SHOW_FLOATING_WIDGET = "show_floating_widget"
        const val ACTION_HIDE_FLOATING_WIDGET = "hide_floating_widget"
        
        /**
         * 启动权限处理Activity
         */
        fun startForAction(context: Context, action: String) {
            val intent = Intent(context, PermissionActivity::class.java).apply {
                putExtra(EXTRA_ACTION, action)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        mediaProjectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        
        // 设置透明主题
        enableEdgeToEdge()
        
        setContent {
            MyApplicationTheme {
                Surface(
                    modifier = androidx.compose.ui.Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background.copy(alpha = 0f) // 完全透明
                ) {
                    PermissionHandler()
                }
            }
        }
    }
    
    @Composable
    private fun PermissionHandler() {
        val action = intent.getStringExtra(EXTRA_ACTION) ?: ""
        
        LaunchedEffect(action) {
            when (action) {
                ACTION_START_RECORDING -> handleStartRecording()
                ACTION_STOP_RECORDING -> handleStopRecording()
                ACTION_SHOW_FLOATING_WIDGET -> handleShowFloatingWidget()
                ACTION_HIDE_FLOATING_WIDGET -> handleHideFloatingWidget()
                else -> {
                    Log.w(TAG, "Unknown action: $action")
                    finish()
                }
            }
        }
    }
    
    private suspend fun handleStartRecording() {
        Log.d(TAG, "Handling start recording request")
        
        // 检查权限
        hasOverlayPermission = Settings.canDrawOverlays(this)
        hasAudioPermission = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.RECORD_AUDIO
        ) == android.content.pm.PackageManager.PERMISSION_GRANTED
        
        if (!hasOverlayPermission) {
            requestOverlayPermission()
            return
        }
        
        if (!hasAudioPermission) {
            requestAudioPermission()
            return
        }
        
        // 所有权限都已获得，请求屏幕录制权限
        requestScreenCapturePermission()
    }
    
    private suspend fun handleStopRecording() {
        Log.d(TAG, "Handling stop recording request")
        ScreenRecordingService.stopRecording(this)
        finish()
    }
    
    private suspend fun handleShowFloatingWidget() {
        Log.d(TAG, "Handling show floating widget request")
        ScreenRecordingService.showFloatingWidget(this)
        finish()
    }
    
    private suspend fun handleHideFloatingWidget() {
        Log.d(TAG, "Handling hide floating widget request")
        ScreenRecordingService.hideFloatingWidget(this)
        finish()
    }
    
    private fun requestOverlayPermission() {
        val intent = Intent(
            Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
            "package:${packageName}".toUri()
        )
        overlayPermissionLauncher.launch(intent)
    }
    
    private fun requestAudioPermission() {
        audioPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
    }
    
    private fun requestScreenCapturePermission() {
        val screenCaptureIntent = mediaProjectionManager?.createScreenCaptureIntent()
        if (screenCaptureIntent != null) {
            screenCaptureLauncher.launch(screenCaptureIntent)
        } else {
            Log.e(TAG, "Failed to create screen capture intent")
            finish()
        }
    }
    
    // 悬浮窗权限请求
    private val overlayPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        hasOverlayPermission = Settings.canDrawOverlays(this)
        if (hasOverlayPermission) {
            // 悬浮窗权限获得，继续检查音频权限
            if (hasAudioPermission) {
                requestScreenCapturePermission()
            } else {
                requestAudioPermission()
            }
        } else {
            Log.w(TAG, "Overlay permission denied")
            finish()
        }
    }
    
    // 音频权限请求
    private val audioPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        hasAudioPermission = isGranted
        if (isGranted) {
            // 音频权限获得，请求屏幕录制权限
            requestScreenCapturePermission()
        } else {
            Log.w(TAG, "Audio permission denied")
            finish()
        }
    }
    
    // 屏幕录制权限请求
    private val screenCaptureLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            Log.d(TAG, "Screen capture permission granted, starting recording service")
            // 启动录制服务
            val serviceIntent = Intent(this, ScreenRecordingService::class.java).apply {
                action = ScreenRecordingService.ACTION_START_RECORDING
                putExtra(ScreenRecordingService.EXTRA_RESULT_CODE, result.resultCode)
                putExtra(ScreenRecordingService.EXTRA_DATA, result.data)
            }
            ContextCompat.startForegroundService(this, serviceIntent)
        } else {
            Log.w(TAG, "Screen capture permission denied")
        }
        finish()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "PermissionActivity destroyed")
    }
}
